package ru.yermak.bookkeeping.account;

import ru.yermak.bookkeeping.ui.ModalForm;
import ru.yermak.bookkeeping.ui.Selector;
import ru.yermak.bookkeeping.common.BookkeeperState;
import ru.yermak.bookkeeping.common.UserDao;
import ru.yermak.bookkeeping.common.Command;
import ru.yermak.bookkeeping.model.Account;

import javax.swing.*;
import java.awt.event.ActionEvent;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;

/**
 * User: harrier
 * Date: Nov 8, 2008
 */
@Scope("action")
@org.springframework.stereotype.Component
public class AccountEditCommand implements Command {
    @Autowired
    private AccountDao accountDao;
    @Autowired
    private ModalForm modalForm;
    @Autowired
    private BookkeeperState bookkeeperState;
    @Autowired
    private UserDao userDao;
    @Autowired
    @AccountQulifier
    private Selector selector;

    @Autowired
    @AccountQulifier("editForm")
    private JComponent accountEditForm;
    @Autowired
    @AccountQulifier("accountName")
    private JTextField accountNameField;
    @Autowired
    @AccountQulifier("accountDesc")
    private JTextArea accountDescField;
    @Autowired
    @AccountQulifier("createFormCurrencies")
    private JComponent accountCurrenciesField;


    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void execute(ActionEvent e) {
        Integer accountId = selector.getSelectedId();
        Account account = accountDao.getById(accountId);
        accountNameField.setText(account.getName());
        accountDescField.setText(account.getDesc());
//        accountEditForm.setValues(new ArrayList<AccountEditForm.Value>());
        boolean result = modalForm.show(accountEditForm);
        if (result) {
            account.setName(accountNameField.getText());
            account.setDesc(accountDescField.getText());
            accountDao.updateAccount(account);
            selector.selectRow(accountId);
        }

    }
}
